<template>
  <div class="add-role">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()">
          <i class="el-icon-arrow-left" />返回
        </span>
        <span>|</span>
        <span>{{ roleId ? '编辑角色' : '添加角色' }}</span>
      </div>
      <div class="right">黑马程序员</div>
    </header>

    <main class="add-main">
      <div class="step-container">
        <el-steps direction="vertical" :active="activeStep">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>

      <div
        v-show="activeStep === 1"
        class="form-container"
      >
        <div class="title">角色信息</div>
        <div class="form">
          <el-form
            ref="roleForm"
            class="form-box"
            :model="roleForm"
            :rules="roleRules"
          >
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="roleForm.roleName" />
            </el-form-item>
            <el-form-item label="角色描述">
              <el-input v-model="roleForm.remark" />
            </el-form-item>
          </el-form>
        </div>
      </div>

      <div
        v-show="activeStep === 2"
        class="form-container"
      >
        <div class="title">权限配置</div>
        <div class="form">
          <div class="tree-wrapper">
            <div
              v-for="item in treeList"
              :key="item.id"
              class="tree-item"
            >
              <div class="tree-title">{{ item.title }}</div>
              <el-tree
                ref="tree"
                :data="item.children"
                show-checkbox
                default-expand-all
                node-key="id"
                highlight-current
                :props="{ label: 'title' }"
                @check="handleTreeCheck"
              />
            </div>
          </div>
        </div>
      </div>

      <div
        v-show="activeStep === 3"
        class="form-container"
      >
        <div class="title">检查并完成</div>
        <div class="form">
          <div class="info">
            <div class="form-item">角色名称：{{ roleForm.roleName }}</div>
            <div class="form-item">角色描述：{{ roleForm.remark }}</div>
            <div class="form-item">角色权限：</div>
            <div class="tree-wrapper">
              <div
                v-for="(item) in disabledTreeList"
                :key="item.id"
                class="tree-item"
              >
                <div class="tree-title">{{ item.title }}</div>
                <el-tree
                  ref="disabledTree"
                  :data="item.children"
                  show-checkbox
                  default-expand-all
                  node-key="id"
                  :highlight-current="false"
                  :props="{ label: 'title'}"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <footer class="add-footer">
      <div class="btn-container">
        <el-button
          v-if="activeStep > 1"
          @click="decreaseStep"
        >
          上一步
        </el-button>
        <el-button
          v-if="activeStep < 3"
          type="primary"
          @click="increaseStep"
        >
          下一步
        </el-button>
        <el-button
          v-if="activeStep === 3"
          type="primary"
          @click="confirmAdd"
        >
          确认{{ roleId ? '编辑' : '添加' }}
        </el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { getTreeListAPI, getRoleDetailAPI, createRoleUserAPI, updateRoleAPI } from '@/api/system'

export default {
  name: 'RoleAdd',

  data() {
    return {
      activeStep: 1,
      roleForm: {
        roleName: '',
        remark: '',
        perms: []
      },
      roleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      treeList: [],
      disabledTreeList: []
    }
  },

  computed: {
    roleId() {
      return this.$route.query.id
    }
  },

  watch: {
    activeStep(newStep) {
      if (newStep === 3) {
        this.$nextTick(() => {
          this.updateDisabledTreeCheckedKeys()
        })
      }
    }
  },

  async created() {
    await this.initData()
  },

  methods: {
    async initData() {
      try {
        await this.getTreeList()
        if (this.roleId) {
          await this.getRoleDetail()
        }
      } catch (error) {
        this.$message.error('初始化数据失败')
      }
    },

    handleTreeCheck() {
      if (this.$refs.tree) {
        this.roleForm.perms = this.$refs.tree.map(tree => tree.getCheckedKeys())
        if (this.activeStep === 3) {
          this.updateDisabledTreeCheckedKeys()
        }
      }
    },

    updateDisabledTreeCheckedKeys() {
      if (this.$refs.disabledTree && this.roleForm.perms) {
        this.$refs.disabledTree.forEach((tree, index) => {
          if (this.roleForm.perms[index]) {
            tree.setCheckedKeys(this.roleForm.perms[index])
          }
        })
      }
    },

    async getRoleDetail() {
      try {
        const { data } = await getRoleDetailAPI(this.roleId)
        const { perms, remark, roleId, roleName } = data
        this.roleForm = { perms, remark, roleId, roleName }

        await this.$nextTick()
        if (this.$refs.tree) {
          this.$refs.tree.forEach((tree, index) => {
            if (this.roleForm.perms[index]) {
              tree.setCheckedKeys(this.roleForm.perms[index])
            }
          })
        }
        if (this.activeStep === 3) {
          this.updateDisabledTreeCheckedKeys()
        }
      } catch (error) {
        this.$message.error('获取角色详情失败')
      }
    },

    async getTreeList() {
      try {
        const { data } = await getTreeListAPI()
        this.treeList = data
        this.disabledTreeList = this.getDisabledTreeList(data)
      } catch (error) {
        this.$message.error('获取权限列表失败')
      }
    },

    getDisabledTreeList(treeList) {
      const clonedList = JSON.parse(JSON.stringify(treeList))
      this.addDisabledToTree(clonedList)
      return clonedList
    },

    addDisabledToTree(treeList) {
      treeList.forEach(item => {
        item.disabled = true
        if (item.children?.length) {
          this.addDisabledToTree(item.children)
        }
      })
    },

    async increaseStep() {
      if (this.activeStep === 1) {
        try {
          await this.$refs.roleForm.validate()
          this.activeStep++
        } catch (error) {
          return
        }
      } else if (this.activeStep < 3) {
        this.activeStep++
      }
    },

    decreaseStep() {
      if (this.activeStep > 1) {
        this.activeStep--
      }
    },

    async confirmAdd() {
      try {
        if (this.roleId) {
          await updateRoleAPI(this.roleForm)
        } else {
          await createRoleUserAPI(this.roleForm)
        }

        this.$message.success(`${this.roleId ? '编辑' : '新增'}角色成功`)
        this.$router.back()
      } catch (error) {
        this.$message.error(`${this.roleId ? '编辑' : '新增'}角色失败`)
      }
    }
  }
}
</script>

  <style lang="scss" scoped>
  .add-role {
    background-color: #f4f6f8;
    height: 100vh;

    .add-header {
      display: flex;
      justify-content: space-between;
      padding: 0 20px;
      height: 64px;
      line-height: 64px;
      font-size: 16px;
      font-weight: bold;
      background-color: #fff;

      .left {
        span {
          margin-right: 4px;
        }

        .arrow {
          cursor: pointer;
        }
      }

      .right {
        text-align: right;
      }
    }

    .add-main {
      position: fixed;
      top: 64px;
      bottom: 88px;
      width: 100%;
      overflow-y: auto;
      background: #f4f6f8;
      padding: 20px 230px;
      display: flex;

      .step-container {
        height: 400px;
        width: 200px;
      }

      .form-container {
        flex: 1;
        background-color: #fff;
        overflow-y: auto;

        .title {
          height: 60px;
          line-height: 60px;
          padding-left: 20px;
        }

        .form {
          margin-bottom: 20px;
          padding: 20px 65px 24px;

          .form-box {
            width: 600px;
            display: flex;
            flex-direction: column;
          }

          .info {
            font-size: 14px;
            color: #666;

            .form-item {
              margin-bottom: 20px;
            }
          }
        }
      }

      .tree-wrapper {
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;

        .tree-item {
          flex: 1;
          padding: 0 4px;
          text-align: center;

          .tree-title {
            background: #f5f7fa;
            text-align: center;
            padding: 10px 0;
            margin-bottom: 12px;
          }
        }
      }
    }

    .add-footer {
      position: fixed;
      bottom: 0;
      width: 100%;
      padding: 24px 50px;
      color: #000000d9;
      font-size: 14px;
      background: #fff;
      text-align: center;
      z-index: 10001;
    }
  }
  </style>
